import { Platform ,normalizeURL} from 'ionic-angular';
import { Injectable } from '@angular/core';
import ImgCache       from 'imgcache.js';
declare var cordova: any; //导入第三方的库定义到 TS 项目中

/*
  Generated class for the CacheimgserviceProvider provider.

  See https://angular.io/guide/dependency-injection for more info on providers
  and Angular DI.
*/
@Injectable()
export class CacheimgserviceProvider {

  constructor(public platform: Platform) {
    ImgCache.options.debug = true;
  }

  /**
   * Init imgCache library
   * @return {Promise}
   */
  public initImgCache(): Promise<any> {
    return new Promise((resolve, reject) => {
      if (ImgCache.ready) {
        resolve();
      } else {
        ImgCache.init(() => resolve(), () => reject());
      }
    });
  }

  /**
   * Cache images
   * @param src {string} - img source
   */
  public cacheImg(src: string): Promise<any> {
    return new Promise((resolve, reject) => {
      ImgCache.isCached(src, (path: string, success: boolean) => {
        // if not, it will be cached
        if (success) {
          ImgCache.getCachedFileURL(src,
            (originalUrl, cacheUrl) => {
              if(this.platform.is('ios')){
              var imgurl = cacheUrl.substr(cacheUrl.lastIndexOf('/') + 1);
              var iosCacheUrl = normalizeURL(cordova.file.applicationStorageDirectory+"Library/files/imgcache/"+imgurl);
              resolve(iosCacheUrl);
              }else{
                resolve(cacheUrl);
              }
              
            },
            (e) => {
              reject(e)
            });
        } else {
          // cache img
          ImgCache.cacheFile(src);
          // return original img URL
          resolve(src);
        }
      });
    });
  }


}
